<template>
  <div id="app">
    <el-container class="app-container">
      <!-- 全局加载状态 -->
      <el-loading
        v-model:loading="isLoading"
        :text="loadingText"
        :background="loadingBackground"
        :fullscreen="true"
      />

      <el-header class="app-header" v-if="!isLoginPage">
        <div class="header-content">
          <div class="logo-section">
            <div class="logo-icon">
              <el-icon :size="24" color="#cdaa52"><Monitor /></el-icon>
            </div>
            <h1 class="app-title">API Pulse</h1>
          </div>

          <div class="nav-section">
            <el-menu
              :default-active="activeMenu"
              mode="horizontal"
              background-color="#f0ebe0"
              text-color="#333"
              active-text-color="#cdaa52"
              @select="handleMenuSelect"
            >
              <el-menu-item index="/">项目管理</el-menu-item>
              <el-menu-item index="/monitor">监控中心</el-menu-item>
              <el-menu-item index="/reports">报表统计</el-menu-item>
            </el-menu>
          </div>

          <div class="actions-section">
            <div class="user-actions">
              <el-dropdown>
                <div class="user-avatar">
                  <el-avatar :size="32" icon="UserFilled" />
                </div>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleUserAction('logout')">退出登录</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </div>
      </el-header>

      <el-main class="app-main">
        <router-view v-slot="{ Component }">
          <transition name="fade" mode="out-in">
            <component :is="Component" @set-loading="handleLoading" />
          </transition>
        </router-view>
      </el-main>

      <el-footer class="app-footer" v-if="!isLoginPage">
        <div class="footer-content">
          <p>© 2023 API Pulse - 接口监控系统. All rights reserved.</p>
        </div>
      </el-footer>
    </el-container>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onBeforeUnmount, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Monitor, SwitchButton, Setting, Plus } from '@element-plus/icons-vue'

export default {
  name: 'App',
  components: {
    Monitor,
    SwitchButton,
    Setting,
    Plus
  },
  setup() {
    console.log('App.vue setup函数开始执行 at:', new Date().toISOString())
    const router = useRouter()
    const route = useRoute()
    
    // 加载状态
    const isLoading = ref(false)
    const loadingText = ref('加载中...')
    const loadingBackground = ref('rgba(255, 255, 255, 0.8)')
    
    // 活动菜单
    const activeMenu = ref('/')
    
    // 判断是否为登录页面
    const isLoginPage = computed(() => {
      return route.path === '/login'
    })
    
    // 组件挂载时
    onMounted(() => {
      console.log('App mounted at:', new Date().toISOString())
      
      // 添加全局错误处理
      window.addEventListener('unhandledrejection', event => {
        console.error('Unhandled promise rejection:', event.reason)
      })
      
      window.addEventListener('error', event => {
        console.error('Global error:', event.error)
      })
    })
    
    // 组件卸载前
    onBeforeUnmount(() => {
      console.log('App unmounted at:', new Date().toISOString())
      
      // 移除事件监听器
      window.removeEventListener('unhandledrejection', () => {})
      window.removeEventListener('error', () => {})
    })
    
    // 处理菜单选择
    const handleMenuSelect = (index) => {
      console.log('菜单选择:', index, 'at:', new Date().toISOString())
      router.push(index)
    }
    
    // 处理用户操作
    const handleUserAction = (command) => {
      console.log('用户操作:', command, 'at:', new Date().toISOString())
      switch (command) {
        case 'logout':
          ElMessageBox.confirm('确定要退出登录吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            // 清除所有认证相关数据
            localStorage.removeItem('token')
            // 添加重定向参数，避免直接跳转登录页
            const currentPath = route.path === '/login' ? '/' : route.path
            router.push({
              path: '/login',
              query: { redirect: currentPath }
            })
            ElMessage.success('已退出登录')
          }).catch(() => {})
          break
      }
    }
    
    // 处理加载状态
    const handleLoading = (loading, text = '加载中...') => {
      isLoading.value = loading
      loadingText.value = text
    }
    
    // 跳转到创建项目页面
    const goToCreateProject = () => {
      router.push('/project/create')
    }
    
    // 跳转到设置页面
    const goToSettings = () => {
      router.push('/settings')
    }
    
    // 退出登录
    const logout = () => {
      handleUserAction('logout')
    }

    // 添加 SwitchButton 到组件中
    return {
      isLoading,
      loadingText,
      loadingBackground,
      activeMenu,
      isLoginPage,
      goToCreateProject,
      goToSettings,
      logout,
      handleMenuSelect,
      handleLoading,
      handleUserAction
    }
  }
}
</script>

<style scoped>
/* 添加过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 其他样式保持不变 */
.app-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

/* ...其他样式保持不变... */
</style>

<style scoped>
.app-container {
  min-height: 100vh;
  background-color: #f9f6e7;
}

.app-header {
  background-color: #f0ebe0;
  padding: 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px;
  height: 64px;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo-icon {
  background-color: white;
  border-radius: 8px;
  padding: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.app-title {
  color: #cdaa52;
  font-size: 20px;
  font-weight: 600;
  margin: 0;
}

.nav-section {
  flex: 1;
  margin: 0 40px;
}

:deep(.el-menu.el-menu--horizontal) {
  border: none;
  background-color: transparent !important;
}

:deep(.el-menu-item) {
  font-size: 14px;
  font-weight: 500;
  border-bottom: none !important;
}

:deep(.el-menu-item:hover) {
  background-color: #e8d8a8 !important;
}

:deep(.el-menu-item.is-active) {
  background-color: #e8d8a8 !important;
  border-bottom: none !important;
}

.actions-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.create-btn {
  background-color: #cdaa52;
  border-color: #cdaa52;
  font-weight: 500;
  transition: all 0.3s;
}

.create-btn:hover {
  background-color: #b38e4a;
  border-color: #b38e4a;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.user-avatar {
  cursor: pointer;
  transition: transform 0.3s;
}

.user-avatar:hover {
  transform: scale(1.05);
}

.app-main {
  padding: 24px;
  min-height: calc(100vh - 128px);
}

.app-footer {
  background-color: #f0ebe0;
  padding: 16px 0;
  border-top: 1px solid #e0d4b4;
}

.footer-content {
  text-align: center;
  color: #666;
  font-size: 14px;
}
</style>